require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIRobTicketPurchase = {}
HelperFunc.SetUIEnv(UIRobTicketPurchase)
local this = UIRobTicketPurchase

function UIRobTicketPurchase.Init(data, closeFunc) 

    local _name, _package = getUIName(PanelNames.UIRobTicketPurchase)
    panelMgr:ShowUI(_name, _package, this.onCreate, Config.useLocalUI)
end

function UIRobTicketPurchase.onCreate(obj) 
    if not this.hasInit then
        this.hasInit = true  
        this.btn_bg_close = obj:GetChild("BgClose")  
        this.btn_buy = obj:GetChild("BuyButton")
        this.item_name = obj:GetChild("ItemName")
        this.item_icon = obj:GetChild("ItemIcon")
        this.txt_remain_count = obj:GetChild("Text_RemainCount")
        this.txt_cost_count = obj:GetChild("CostCount")

        this.addEvent()
    end 
    this.initData()
end
 
function UIRobTicketPurchase.initData() 

    local up_count = dataTable.getDataTableByStringId("t_global", 324 ,"f_int_value") 
    local own_count = up_count - plunderHandler.cur_buy_plunder_count
    this.txt_remain_count.text = tostring(own_count) 


    local own_num = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD) or 0
    local need_num = dataTable.getDataTableByStringId("t_global", 323 ,"f_int_value") 
    this.txt_cost_count.text = tostring(own_num) .. "/" .. tostring(need_num) 
    
    if own_num >= need_num then
        this.txt_cost_count.text = getNumString(own_num) .. "/" .. tostring(need_num) 
    else 
        this.txt_cost_count.text = table.concat({string.TextColor(getNumString(own_num),"#FF0000"), "/", tostring(need_num)})
    end

    local cfg = dataTable.getDataTableByStringId("t_item", 200005)
    if cfg ~= nil then
        this.item_name.text = getLanguage(cfg.f_ItemName)
        this.item_icon.url = "ui://ItemAtlas/"..cfg.f_Icon
    end
end
 


function UIRobTicketPurchase.addEvent() 
    this.btn_bg_close.onClick:Add(this.CloseSelf)    
    this.btn_buy.onClick:Add(this.ClickBuy)
end

function UIRobTicketPurchase.removeEvent() 
    this.btn_bg_close.onClick:Clear()   
    this.btn_buy.onClick:Clear()
end

function UIRobTicketPurchase.CloseSelf() 
    closeUI(PanelNames.UIRobTicketPurchase)
end
    
function UIRobTicketPurchase.ClickBuy()   
    local own_num = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD) or 0
    local need_num = dataTable.getDataTableByStringId("t_global", 323 ,"f_int_value") 
    if own_num >= need_num then
        plunderHandler.sendReqBuyPlunderItem()
        closeUI(PanelNames.UIRobTicketPurchase)
    else
        UISysTips.AddMsg(getLanguage("Character_Tips7"))
    end 
end

function UIRobTicketPurchase.OnDestroy() 
    this.removeEvent()
    this.hasInit = nil 
    this.btn_bg_close = nil 
    this.btn_buy = nil 
    this.item_name = nil 
    this.item_icon = nil 
    this.txt_remain_count = nil 
    this.txt_cost_count = nil 
end

return UIRobTicketPurchase
